package com.whj.handler;

import com.alibaba.fastjson.JSONObject;
import com.whj.common.agreement.RpcRequest;
import com.whj.service.Context;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Whj extends ChannelInboundHandlerAdapter {
    /**
     *
     * @param ctx 用来给客户端发消息
     * @param msg 客户端传来的字符串数据 - 当然在这里可以根据客户端传来的数据的格式进行传输协议的规则定义
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = JSONObject.parseObject(msg.toString(), RpcRequest.class);
        String methodName = rpcRequest.getMethodName();
        String requestId = rpcRequest.getRequestId();

        ApplicationContext applicationContext = Context.getApplicationContext();
        Object bean = applicationContext.getBean(requestId);
        Method method = getMethod(bean.getClass(), methodName);
        //调用bean的method方法，参数objects
        method.invoke(bean);
        System.out.println("bean: "+bean);
        System.out.println(rpcRequest);
        ctx.writeAndFlush("success");

    }



    /**
     * 获取目标方法
     * @param proxyObject
     * @param methodStr
     * @return
     */
    private Method getMethod(Class proxyObject, String methodStr) {
        Method[] methods = proxyObject.getMethods();

        for(Method method : methods) {
            if(method.getName().equalsIgnoreCase(methodStr)) {
                return method;
            }
        }

        return null;
    }
}
